package com.ranjiaqi.testreflact;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName HomeWork01
 * @Description TODO
 * @Author hp
 * @Date 2021/7/5 18:30
 * @Version 1.0
 **/
public class HomeWork {
    @Test
    public   void  homeWork01() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<?> name = Class.forName("com.ranjiaqi.testreflact.Student");
        Constructor<?> constructor = name.getConstructor();
        Object obj = constructor.newInstance();
        Constructor constructor1 = name.getConstructor(String.class,int.class);
        Object o = constructor1.newInstance("张三",18);
    }
    @Test
    public void homeWork02() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class<?>   cla = Class.forName("com.ranjiaqi.testreflact.Mytxt");
        Object obj = cla.newInstance();
        Method method = cla.getMethod("myCreate");
        method.invoke(obj);
    }

    @Test
    public void homeWork03() throws Exception{
       Class cla =  Class.forName("com.ranjiaqi.testreflact.PrivateTest");
       Field field = cla.getDeclaredField("name");
       Object obj = cla.newInstance();
       Method method = cla.getMethod("getName");
       field.setAccessible(true);
       field.set(obj,"崔为她戒掉了烟，踢掉了头上的莫西干");
        System.out.println(method.invoke(obj));
    }

    @Test
    public void homeWork04()throws Exception{
        Class<?> cla = Class.forName("java.io.File");
        Constructor<?>[] constructors = cla.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        Constructor<?> constructor = cla.getConstructor(String.class);
        Object obj = constructor.newInstance("D:/mynew.txt");
        Method method = cla.getMethod("createNewFile");
        Object invoke = method.invoke(obj);
        System.out.println(invoke);
    }
}